package com.sws.worktive.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import ch.boye.httpclientandroidlib.client.HttpClient;

import com.sws.worktive.jobs_fetcher.JobFetcher;
import com.sws.worktive.util.Constant;
import com.sws.worktive.util.HttpMethod;

public class ServerDownload extends
		AsyncTask<List<NameValuePair>, Void, JSONObject> {

	InputStream is = null;
	JSONObject jObj = null;
	String json = "";

	Context mContext;
	ServerResponse mResponse;
	String requestTag;
	ch.boye.httpclientandroidlib.HttpEntity httpEntity;
	
	
	public ServerDownload(Context context, ServerResponse serverResponse,
			String requestTag, ch.boye.httpclientandroidlib.HttpEntity entity){
		mContext = context;
		mResponse = serverResponse;
		this.requestTag = requestTag;
		this.httpEntity = entity;
	}

	public ServerDownload(Context context, ServerResponse serverResponse,
			String requestTag) {
		this(context, serverResponse, requestTag, null);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected JSONObject doInBackground(List<NameValuePair>... params) {
		if (params[0] == null) {
			if (requestTag.equals(Constant.TAG_JOB_REQUEST)) {
				getJSONFromUrl(JobFetcher.JOBS_URL, null, HttpMethod.GET);
			} else if (requestTag.equals(Constant.TAG_CATEGORY_REQUEST)) {
				getJSONFromUrl(Constant.CATEGORY_API, null, HttpMethod.GET);
			}

		} else {
			if(requestTag.equals(Constant.SIGNIN_FRAGMENT)){
				getJSONFromUrl(Constant.SERVER_AUTH, params[0], HttpMethod.POST);
			}else if(requestTag.equals(Constant.SIGNUP_FRAGMENT)){
				getJSONFromUrl(Constant.SERVER_SAVE, params[0], HttpMethod.POST);
			}else if (requestTag.equals(Constant.TAG_POST_REQUEST)){
				if (httpEntity != null) {
					getJSONFromUrl(Constant.SERVER_URL, params[0], HttpMethod.POST, httpEntity);
				}else {
					getJSONFromUrl(Constant.SERVER_URL, params[0], HttpMethod.POST);
				}
			}
		}
		return jObj;
	}

	@Override
	protected void onProgressUpdate(Void... values) {
		super.onProgressUpdate(values);
	}

	@Override
	protected void onPostExecute(JSONObject result) {
		super.onPostExecute(result);
		mResponse.httpResponse(result, requestTag);
	}
	
	public JSONObject getJSONFromUrl(String url, List<NameValuePair> params,
			HttpMethod method, ch.boye.httpclientandroidlib.HttpEntity entity) {
		// Making HTTP request
				try {
					// defaultHttpClient
					HttpClient httpClient = new ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient();
					ch.boye.httpclientandroidlib.HttpResponse httpResponse = null;
					switch (method) {
					case POST:
						ch.boye.httpclientandroidlib.client.methods.HttpPost httpPost = new ch.boye.httpclientandroidlib.client.methods.HttpPost(url);
						
						httpPost.setEntity(entity);
						
						httpResponse = httpClient.execute(httpPost);
						break;
					default:
						return null;

					}

					ch.boye.httpclientandroidlib.HttpEntity httpEntity = httpResponse.getEntity();
					is = httpEntity.getContent();
					
					entity.consumeContent();
					httpClient.getConnectionManager().shutdown();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					json = sb.toString();
					Log.e("JSON", json);
				} catch (Exception e) {
					Log.e("Buffer Error", "Error converting result " + e.toString());
				}

				// try parse the string to a JSON object
				try {
					if (requestTag.equals(Constant.TAG_CATEGORY_REQUEST)) {
						JSONArray jsonArray = new JSONArray(json);
						jObj = new JSONObject();
						jObj.put("response", jsonArray);
					} else {
						jObj = new JSONObject(json);
					}

				} catch (JSONException e) {
					Log.e("JSON Parser", "Error parsing data " + e.toString());
				}

				return jObj;
		
	}

	public JSONObject getJSONFromUrl(String url, List<NameValuePair> params,
			HttpMethod method) {
		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpResponse httpResponse = null;
			switch (method) {
			case POST:
				HttpPost httpPost = new HttpPost(url);
				
					httpPost.setEntity(new UrlEncodedFormEntity(params));
				
				httpResponse = httpClient.execute(httpPost);
				break;
			case PUT:
				HttpPut httpPut = new HttpPut(url);
				httpPut.setEntity(new UrlEncodedFormEntity(params));
				httpResponse = httpClient.execute(httpPut);
				break;
			case DELETE:
				HttpDelete httpDelete = new HttpDelete(url);
				httpResponse = httpClient.execute(httpDelete);
				break;
			case GET:
				if (params != null && params.size() > 0) {
					if (url.indexOf("?") > 0) {
						if (url.indexOf("?") != url.length() - 1) {
							url = url + "&";
						}
					} else {
						url = url + "?";
					}
					url = url + new UrlEncodedFormEntity(params);
				}
				HttpGet httpGet = new HttpGet(url);
				httpGet.setHeader("Authorization", "Basic cmVzOmhlcm8=");
				httpResponse = httpClient.execute(httpGet);

				break;
			case CURL:
				try {
					URI uri = new URI("https://AC2253899c7f2f8f7e1fbc36707d554b5e:8edc9c50b3e93c81f8631dbd0cc67886@api.twilio.com/2010-04-01/Accounts/AC2253899c7f2f8f7e1fbc36707d554b5e/Messages.json");
					HttpGet httpPostcurl = new HttpGet(uri);
					httpResponse = httpClient.execute(httpPostcurl);
					
				} catch (URISyntaxException e) {
					e.printStackTrace();
				}
			break;
			
			default:
				return null;

			}

			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			Log.e("JSON", json);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			if (requestTag.equals(Constant.TAG_CATEGORY_REQUEST)) {
				JSONArray jsonArray = new JSONArray(json);
				jObj = new JSONObject();
				jObj.put("response", jsonArray);
			} else {
				jObj = new JSONObject(json);
			}

		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		return jObj;

	}

}
